﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using System.Data;
using System.Collections;

public partial class SubscriptionInternals : System.Web.UI.Page
{

    Dictionary<string, string> d = new Dictionary<string, string>();
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["proid"] != null)
            {
           
                ViewState.Add("myitems", d);
                ViewState.Add("olditems", d);
                DataRow drr = ((DataSet)DB.getdata(" select c.* ,p.product from company_product c inner join products p on(c.product_id = p.id) where c.id =" + Request.QueryString["proid"])).Tables[0].Rows[0];
                  ViewState["copys"] = drr["copyno"].ToString();
               //   copys.Text = ViewState["copys"].ToString();
                ends.Text = drr["enddate"].ToString();
                ViewState["enddate"] = drr["enddate"].ToString();
                product.Text = drr["product"].ToString();
                
                adjustclient(int.Parse(Session["company_id"].ToString()));
            }
        }
        else
        {
            
            d = (Dictionary<string, string>)ViewState["myitems"];
            if (d.Count > 0)
            {   ClearImageList();
                foreach (KeyValuePair<string, string> k in d)
                {

                    createImageListItem(k.Value.Split(',')[0], k.Key, k.Value.Split(',')[1]);

                }


            }
        
        }
    }
    protected void ClearImageList()
    {
        for (int i = 0; i < ListT.Controls.Count; i++)
        {
            if (ListT.Controls[i] is ImageListItem)
            {
                ListT.Controls.Remove(ListT.Controls[i]);
            }
        }

    }
    public void adjustclient(Int64 id)
    {
        string select = "select i.*,c.*, i.id as mypro from internal_distribution i inner join internal_copies c on (i.id=c.internal_id) where c.company_product_id=" + Request.QueryString["proid"] ;
        DataSet ds = DB.getdata(select);
        //////////////adjust main info//////////////////////////
        string myids = "";
        int x = int.Parse(ViewState["copys"].ToString());
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            d.Add(dr["mypro"].ToString(), dr["name"].ToString() + "," + dr["assumedcopyno"].ToString());
           // old.Add(dr["id"].ToString(), dr["product"].ToString() + "," + dr["puplisher_id"].ToString());
            x -= int.Parse(dr["assumedcopyno"].ToString());

            myids += dr["mypro"].ToString() + ",";
            createImageListItem(dr["name"].ToString(), dr["mypro"].ToString(), dr["assumedcopyno"].ToString());
        
        }
        ViewState["copys"] = x;
        copys.Text = ViewState["copys"].ToString();
       
        ViewState["olditems"]= d;
        ViewState["myitems"] = d;
            GridView1.DataBind();

    }
    protected void DivClick(object sender, EventArgs e)
    {

        string bb = ((HiddenField)((System.Web.UI.HtmlControls.HtmlGenericControl)sender).FindControl("myvalue")).Value;

        ImageListItem dd = (ImageListItem)ListT.FindControl(bb);
        int xx = int.Parse(ViewState["copys"].ToString()) + int.Parse(dd.Data);
        ViewState["copys"] = xx.ToString();
        copys.Text = xx.ToString();
        ListT.Controls.Remove(dd);
        ListT.DataBind();
        d.Remove(bb);
        editgrid();
       
        ViewState["myitems"] = d;

    }
    protected void createImageListItem(string text, string value,string data)
    {
        ImageListItem myUserControl = (ImageListItem)Page.LoadControl("~/ImageListItem.ascx");
        myUserControl.DisplayText = text + "&nbsp;&nbsp;&nbsp;" + "عدد النسخ المفترضة" + "&nbsp;&nbsp;" + data;
        myUserControl.Values = value;
        myUserControl.Data = data;
        myUserControl.DivClick += new EventHandler(DivClick);
        myUserControl.ID = value;

        ListT.Controls.Add(myUserControl);

    }
    //http://www.facebook.com/hussien.elaraby1
    //   //fb.me/9UWGUK4vxs650W

    protected override void InitializeCulture()
    {
        if (Session["CurrentCulture"] != null)
        {
            string lang = Session["CurrentCulture"].ToString();
            if (lang != null && lang != "")
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
                Thread.CurrentThread.CurrentCulture.DateTimeFormat = new CultureInfo("en-US", false).DateTimeFormat;
                // Thread.CurrentThread.CurrentCulture.Calendar=new  System.Globalization.GregorianCalendar();

            }
        }

    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
      
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    e.Row.Attributes.Add("onmouseover", "this.Mystyle=this.style.backgroundColor;this.style.backgroundColor='#FFFFA8'");

        //    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.Mystyle");
        //}
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {

    }
    
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chk=(CheckBox)sender;
        GridViewRow gr = (GridViewRow)chk.NamingContainer;
        string copy = ((TextBox)gr.FindControl("copyno")).Text;
        int ff=int.Parse(ViewState["copys"].ToString());
        if ((int.Parse(copy) <= ff) && (ff>0))
        {
        string[]sts=chk.ToolTip.Split(',');
        createImageListItem(sts[1], sts[0], copy);

        d.Add(sts[0], sts[1] + "," + copy);
         int xx = ff - int.Parse(copy);

          copys.Text= xx.ToString();
         ViewState["copys"] = xx.ToString();
        editgrid();
     
        ViewState["myitems"] = d;
        }
        else
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "hj", "alert('النسخ غير المسموح');", true);

      // Page.ClientScript.RegisterStartupScript(this.GetType(), "reports", "alert('النسخ اكبر من المسموح');", true);
        chk.Checked = false;
        
        }
        
    }
    public void editgrid()
    {
        d = (Dictionary<string,string>) ViewState["myitems"];
        if (d.Count > 0)
        {
            string myids = "";
            foreach (KeyValuePair<string, string> k in d)
            {
                myids += k.Key + ",";
            }
            myids = myids.Trim(",".ToCharArray()[0]);
            SqlDataSource1.SelectCommand = "select * from  internal_distribution where id not in(" + myids + ")";
          
        }
        else
        {

            SqlDataSource1.SelectCommand = "select * from  internal_distribution";
        }
        GridView1.DataBind();
        
    }
    protected void save_Click(object sender, EventArgs e)
    {
        Dictionary<string, string> myitems = (Dictionary<string, string>)ViewState["myitems"];
        Dictionary<string, string> olditems = (Dictionary<string, string>)ViewState["olditems"];


      //  DB.DELETE("company_product", "int,company_id," + Session["company_id"].ToString());
        List<string> fields = new List<string>();
        ArrayList values = new ArrayList();
        List<string> types = new List<string>();
       

        foreach (var key in olditems)
        {
            if (!myitems.ContainsKey(key.Key))
            {
                DB.DELETE("internal_copies", "int,internal_id," + key.Key);
            }
        }
        // Inserting new keys that doesnot exist in olditems list 
        foreach (var key in myitems)
        {
            if (!olditems.ContainsKey(key.Key))
            {
                fields.Clear();
                types.Clear();
                values.Clear();
                //////////////////
                fields.Add("internal_id");
                types.Add("int");
                values.Add(key.Key);
                ///////////////////////

                fields.Add("company_product_id");
                types.Add("int");
                values.Add(Request.QueryString["proid"]);
                ///////////////////////
                ///////////////////////

                fields.Add("assumedcopyno");
                types.Add("int");
                values.Add(key.Value.Split(',')[1]);
                ///////////////////////
                DateTime c = DateTime.Parse(ViewState["enddate"].ToString());
                fields.Add("enddate");
                types.Add("datetime");
                values.Add(c.ToShortDateString());
                /////////////////////////////
                int ff = (int)DB.INSERT("internal_copies", fields, types, values);
            }
        }
        Page.ClientScript.RegisterStartupScript(this.GetType(), "reports", "alert('تم التسجيل بنجاج');", true);
        ViewState["olditems"] = ViewState["myitems"];

        //if (ListT.Controls.Count > 1)
        //{
        //    for (int i = 1; i < ListT.Controls.Count; i++)
        //    {
        //        ImageListItem dd = (ImageListItem)ListT.Controls[i];
        //        //////////
        //        if (d.ContainsKey(dd.Values))
        //        {

        //            d.Remove(dd.Values);
        //        }
        //        else
        //        {


        //            fields.Clear();
        //            types.Clear();
        //            values.Clear();
        //            //////////////////
        //            fields.Add("internal_id");
        //            types.Add("int");
        //            values.Add(dd.Values);
        //            ///////////////////////

        //            fields.Add("company_product_id");
        //            types.Add("int");
        //            values.Add(Request.QueryString["proid"]);
        //            ///////////////////////
        //            ///////////////////////

        //            fields.Add("assumedcopyno");
        //            types.Add("int");
        //            values.Add(dd.Data);
        //            ///////////////////////
        //            DateTime c = DateTime.Parse(ViewState["enddate"].ToString());
        //            fields.Add("enddate");
        //            types.Add("datetime");
        //            values.Add(c.ToShortDateString());
        //            /////////////////////////////
        //            int ff = (int)DB.INSERT("internal_copies", fields, types, values);
        //        }
                   
        //    }
        //}
        //    if (d.Count > 0)
        //    {
        //        foreach (KeyValuePair<string, string> k in d)
        //        {
        //            DB.DELETE("internal_copies", "int,internal_id," + k.Key);
        //          //  DB.DELETE("daily_checking", "int,company_product_id," + k.Key);
        //        }
            
            
           
        //  //  Page.ClientScript.RegisterStartupScript(this.GetType(), "reports", "alert('تم التسجيل بنجاج');", true);
             
        //}
        //    Response.Redirect("~/companypart/CompanySubscription.aspx");
        ////////////////////////////////////////////////////////

    }

    
   
}
